package com.nbsaas.boot.advice;

import com.google.gson.Gson;
import com.nbsaas.boot.rest.annotations.EncryptionData;
import com.nbsaas.boot.rest.response.ResponseObject;
import org.apache.shiro.codec.Base64;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@ControllerAdvice
public class ResponseEncryptionAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 在这里可以根据条件来确定是否需要加密响应
        return true; // 这里返回true表示对所有响应数据进行加密
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResponseObject<?>) {
            Object obj = ((ResponseObject<?>) body).getData();
            if (obj == null) {
                return body;
            }
            EncryptionData data = returnType.getMethodAnnotation(EncryptionData.class);
            if (data == null) {
                return body;
            }
            ResponseObject<String> responseObject = new ResponseObject<>();
            String json = new Gson().toJson(body);
            RequestBodyDecodeAdvice advice = new RequestBodyDecodeAdvice();
            try {
                byte[] dd = advice.encrypt(json.getBytes(), RequestBodyDecodeAdvice.AES_KEY);
                responseObject.setData(Base64.encodeToString(dd));

            } catch (InvalidKeyException e) {
                throw new RuntimeException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            } catch (NoSuchPaddingException e) {
                throw new RuntimeException(e);
            } catch (IllegalBlockSizeException e) {
                throw new RuntimeException(e);
            } catch (BadPaddingException e) {
                throw new RuntimeException(e);
            }

            return responseObject;
        }
        return body;
    }
}
